package cz.possoft.client.loader;

import java.io.File;

/**
 * Deployment util methods.
 * 
 * @author mposolda
 *
 */
class DeploymentUtils {
	
	private DeploymentUtils() {}
	
	/**
	 * Util helper method for obtaining correct key based on the classname.
	 * Examples: 
	 * Input: FourClient-1.4-SNAPSHOT.jar, output: Four
	 * Input: ChessGeneric-1.4-SNAPSHOT.jar, output: Chess 
	 * 
	 * @param filename
	 * @return
	 */
	static String getPrefixForJarFile(String filename) {
		if (filename.contains("Generic")) {
			int index = filename.indexOf("Generic");
			return filename.substring(0, index);
		}
		else if (filename.contains("Client")) {
			int index = filename.indexOf("Client");
			return filename.substring(0, index);
		}
		else {
			throw new IllegalArgumentException("Filename " + filename + " is not valid filename for obtaining prefix.");
		}
	}	
	
	/**
	 * Input can be name of generic jar file or client jar file. Output is generic jar file corresponding to the input.
	 * 
	 * Examples:
	 * Input: FourClient-1.4-SNAPSHOT.jar, output: FourGeneric-1.4-SNAPSHOT.jar
	 * Input: ChessGeneric-1.4-SNAPSHOT.jar, output: ChessGeneric-1.4-SNAPSHOT.jar
	 */
	static String getGenericJarFileName(String fileName) {
		if (fileName.contains("Generic")) {
			return fileName;
		}
		else if (fileName.contains("Client")) {
			return fileName.replaceFirst("Client", "Generic");
		}
		else {
			throw new IllegalArgumentException("Filename " + fileName + " is not valid filename for getting generic jar file.");
		}
	}
	
	/**
	 * Input can be name of generic jar file or client jar file. Output is client jar file corresponding to the input.
	 * 
	 * Examples:
	 * Input: FourClient-1.4-SNAPSHOT.jar, output: FourClient-1.4-SNAPSHOT.jar
	 * Input: ChessGeneric-1.4-SNAPSHOT.jar, output: ChessClient-1.4-SNAPSHOT.jar
	 */	
	static String getClientJarFileName(String fileName) {
		if (fileName.contains("Client")) {
			return fileName;
		}
		else if (fileName.contains("Generic")) {
			return fileName.replaceFirst("Generic", "Client");
		}
		else {
			throw new IllegalArgumentException("Filename " + fileName + " is not valid filename for getting client jar file.");
		}
	}
	
	/**
	 * @param key
	 * @param files
	 * @param genericFlag - if true, then output is name of generic jar file. Otherwise output is name of client jar file.
	 * @return
	 */
	static String getFileNameFromKeyAndFiles(String key, File[] files, boolean genericFlag) {
		for (File file : files) {
			String fileName = file.getName();
			if (fileName.contains(key)) {
				if (genericFlag) {
					if (fileName.contains("Generic")) {
						return fileName;
					}
				}
				else {
					if (fileName.contains("Client")) {
						return fileName;
					}
				}
			}
		}
		return null;
	}
}
